import fs from 'fs'
import client from './client'
import util from '../utils'
import path from 'path'
import config from '../config'
class Auth {
  //检查本地存储token
  async checkStorageToken() {
    let file = path.join(__dirname, 'token.json')
    let tokenStr = await fs.readFileSync(file, 'utf8')
    let token = JSON.parse(tokenStr)
    let now = Date.now()
    if (token.subJectToken && token.expire > now) {
      return {
        value: token.subJectToken,
        expire: token.expire
      }
    } else {
      return null
    }
  }
  //实时取token
  async fetchToken() {
    console.log('start fetch token...')
    let url = await util.generateRquestUrl('keystone', 'authToken')
    let data = {
      auth: {
        identity: {
          methods: ['password'],
          password: { user: { id: config.userId, password: config.password } }
        },
        scope: { project: { id: config.projectId } }
      }
    }
    try {
      let res = await client.post(url, data)
      let subJectToken = res.headers['x-subject-token']
      let expire = Date.now() + 2 * 60 * 60 * 1000
      let token = {
        subJectToken,
        expire,
        detail: res.token
      }
      await this.saveToken(token)
      return {
        expire,
        value: subJectToken
      }
    } catch (e) {
      console.log('token获取异常')
      return null
    }
  }
  async saveToken(token) {
    let file = path.join(__dirname, 'token.json')
    await fs.writeFileSync(file, JSON.stringify(token))
  }
  async checkTokenExpire() {}
}

export default Auth
